#include <sys/mman.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

int main()
{
    int fd = open("test.txt",O_RDWR | O_CREAT | O_TRUNC,0644);
    ftruncate(fd,4000);
    //创建内存映射区
    void* ptr = mmap(NULL,4000,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
    if(ptr == MAP_FAILED)
    {
        perror("mmap");
        exit(0);
    }
    pid_t pid = fork();
    if(pid > 0)
    {
        usleep(1);
        printf("从映射区读出数据：%s\n",(char*)ptr);
    }
    else
    {
        const char* pt = "我是父进程，我在写入数据";
        memcpy(ptr,pt,strlen(pt) + 1);
    }
    munmap(ptr,4000);
    return 0;
}
